import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useNurseGoods } from '@/service';
import { getNightList, getUrgentList, getExpertList, getDistanceList } from '@/service/api/nurse_goods';
import Taro from '@tarojs/taro';
import { request } from '@/service/request';

export const useMedicationStore = defineStore('medication-store', () => {
  // State
  const beginDate = ref('');
  const endDate = ref('');
  const unitTime = ref(1);
  const family = ref<any>({});
  const duration = ref(0);
  const price = ref(0);
  const times = ref(1);
  const remark = ref('');
  
  // 加急
  const urgent = ref({
    choose: false,
    fee: 0,
    cur: {},
    options: [
      { text: '3-6小时入户加400(不含夜班)', fee: 400 },
      { text: '6-24小时入户加200(不含夜班)', fee: 200 },
      { text: '24-48小时入户加0(不含夜班)', fee: 0 },
    ],
  });
  
  // 夜班
  const night = ref({
    choose: false,
    fee: 0,
    price: 1000,
    options: []
  });
  
  // 节假日
  const festival = ref({
    choose: false,
    fee: 0,
  });
  
  // 专家
  const expert = ref({
    choose: false,
    fee: 0,
    cur: {},
    options: [
      { text: '0元', fee: 0 },
      { text: '200元', fee: 200 },
      { text: '400元', fee: 400 },
      { text: '600元', fee: 600 },
    ],
  });
  
  // 接送
  const pickup = ref({
    choose: false,
    fee: 0,
    price: 3000,
  });
  
  // 规格
  const sku = ref({
    fee: 0,
    cur: {},
    options: [],
  });
  
  // 距离
  const distance = ref({
    num: 0,
    times: 0,
    fee: 0,
    id: -1,
    options: [ ],
  });

  // Computed getters  
  const baseFare = computed(() => {
    // return distance.value.options[0]?.fee || 0;
    const options = distance.value.options;
    
    if (!options.length) {
      return 0;
    }
    
    // 获取各个费用规则
    const baseFareRule = options.find((option: any) => option.feeType === "1"); // 起步价
    console.log('baseFareRule 😂😂', baseFareRule);
    return baseFareRule?.fee || 0;
  });

  const urgentFree = computed(() => {
    return  urgent.value.cur?.fee || 0;
  });

  const nightFree = computed(() => {
    return night.value.choose ? night.value.options[0]?.fee : 0;
  });

  const expertFree = computed(() => {
    return expert.value.cur?.fee || 0;
  });

  const expertTotalFee = computed(() => {
    let total = expertFree.value;
    if(festival.value.choose){
      total += expertFree.value;
    }
    total += expertFree.value * overTimes.value;
    return  Math.round(total * 100) / 100;
  });

  const distanceTotalFee = computed(() => {
    let total = distanceFee.value;
    total += baseFare.value * overTimes.value;
    total += pickup.value.choose ? distanceFee.value : 0;
    total += festival.value.choose ? baseFare.value : 0;
    return total;
  });

  const distanceFee = computed(() => {
    const distanceNum = distance.value.num;
    const options = distance.value.options;
    
    if (!options.length) {
      return 0;
    }
    
    let totalFee = 0;
    
    // 获取各个费用规则
    const baseFareRule = options.find((option: any) => option.feeType === "1"); // 起步价
    const midRangeRule = options.find((option: any) => option.feeType === "2"); // 5-10公里
    const longRangeRule = options.find((option: any) => option.feeType === "3"); // 10公里以上
    
    // 起步价（必须有）
    if (baseFareRule) {
      totalFee += baseFareRule.fee;
      distance.value.id = baseFareRule.id;
    }
    
    // 5-10公里段费用
    if (midRangeRule && distanceNum >= midRangeRule.beginKm) {
      if (distanceNum <= midRangeRule.endKm) {
        // 距离在5-10公里之间
        totalFee += midRangeRule.fee;
        distance.value.id = midRangeRule.id;
      } else {
        // 距离超过10公里，5-10公里段全额收取
        totalFee += midRangeRule.fee;
        distance.value.id = midRangeRule.id;
      }
    }
    
    // 10公里以上费用（按公里计算）
    if (longRangeRule && distanceNum > longRangeRule.beginKm) {
      const extraDistance = distanceNum - longRangeRule.beginKm;
      totalFee += extraDistance * longRangeRule.fee;
    }
    
    return Math.round(totalFee * 100) / 100;
  });

  const festivalFree = computed(() => {
    console.log('baseFare.value 😂😂', baseFare.value);
    console.log('expertFree.value 😂😂', expertFree.value);
    return festival.value.choose ? baseFare.value + expertFree.value: 0;
  });

  const pickupFree = computed(() => {
    return pickup.value.choose ? distanceFee.value : 0;
  });

  const overtimeFee = computed(() => {
    return overTimes.value * (baseFare.value + expertFree.value);
  });

  const overTimes = computed(() => {
    if (!beginDate.value || !endDate.value) {
        return 0;
      }
      
      const startTime = new Date(beginDate.value);
      const endTime = new Date(endDate.value);
      
      // 计算时间差（毫秒）
      const timeDiff = endTime.getTime() - startTime.getTime();
      const min = duration.value || 60;
      const hours = Math.ceil(timeDiff / (1000 * 60 * min));
      return Math.max(hours - 1, 0);
  });

  const totalFee = computed(() => {
    const t = price.value + urgentFree.value + nightFree.value + expertFree.value + distanceFee.value + festivalFree.value + pickupFree.value + overtimeFee.value;
    return t * times.value;
});

  // Actions
  async function loadSku(code:string) {

    request.get('/standard_price/standardPrice/list', {
        code,
      }, {
        useErrMsg: true
      }).then((res:any) => {
        console.warn("res==== info price", res)
        if(res.success.records.length > 0) {
          sku.value.options = res.success.records;
          sku.value.cur = sku.value.options[0];
        }
          else{
            Taro.showToast({
              title: '商品规格不存在',
              icon: 'none'
            })
        }
      })

  }

  const durationText = computed(() => {
    let t = duration.value || 60;
    if(t < 60){
      return t + '分钟';
    }else{
      let h = Math.floor(t / 60);
      let m = t % 60;
      let str = h + '小时';
      if(m > 0){
        str += m + '分钟';
      }
      return str;
    }
  });

  async function init() {
    try {
     remark.value = '';
     beginDate.value = '';
     endDate.value = '';
     night.value.choose = false;
     urgent.value.choose = false;
     urgent.value.cur = {};
     expert.value.choose = false;
     expert.value.cur = {};
     festival.value.choose = false;
     pickup.value.choose = false;
     pickup.value.fee = 0;
     sku.value.fee = 0;
     distance.value.num = 0;
    
      // 初始化夜班费用列表
      const nightResult = await getNightList();
      console.log('nightResult 😂😂', nightResult);
      night.value.options = nightResult.success?.records || [];
      
      // 初始化加急费用列表
      const urgentResult = await getUrgentList({});
      console.log('urgentResult 😂😂', urgentResult);
      urgent.value.options = urgentResult.success?.records || [];

      // 初始化专家费用列表
      const expertResult = await getExpertList();
      console.log('expertResult 😂😂', expertResult);
      expert.value.options = expertResult.success?.records || [];

      // 初始化距离费用列表
      const distanceResult = await getDistanceList();
      console.log('distanceResult 😂😂', distanceResult);
      distance.value.options = distanceResult.success?.records || [];

      console.log('商品列表初始化完成');
    } catch (error) {
      console.error('商品列表初始化失败:', error);
    }
  }

  // 返回所有状态、getters 和 actions
  return {
    durationText,
    distanceTotalFee,
    expertTotalFee,
    remark,
    times,
    totalFee,
    price,
    family,
    duration,
    // State
    beginDate,
    endDate,
    unitTime,
    urgent,
    night,
    festival,
    expert,
    pickup,
    distance,
    sku,
    
    // Getters (computed)
    baseFare,
    urgentFree,
    nightFree,
    expertFree,
    distanceFee,
    festivalFree,
    pickupFree,
    overtimeFee,
    
    // Actions
    loadSku,
    init
  };
});

